from EaseXML import *
import pprint
from urllib2 import urlopen, URLError

class Schedule(XMLObject):
    _name = 'schedule'
    _encoding = 'utf-8'
    Days = ListNode('Day')
    
    @classmethod
    def loadFromUrl(cls, url):
        try:
            data = urlopen(url).read()
            return cls.fromXml(data)
        except URLError, e: 
            print e
    
class Day(XMLObject):
    _name = 'DAY'
    attr = StringAttribute()
    times = ListNode('Time')
    
class Time(XMLObject):
    _name = 'time'
    attr = StringAttribute()
    Shows = ListNode('Show')
    
class Show(XMLObject):
    _name = 'show'
    name = StringAttribute()
    network = TextNode(optional=True)
    title = TextNode(optional=True)
    ep = TextNode(optional=True)
    link = TextNode(optional=True)
    
if __name__ == "__main__":
    url = 'http://services.tvrage.com/feeds/fullschedule.php?country=US'
    doc = Schedule.loadFromUrl(url)
    print 'Loaded URL from TVRage \n'
    #XML = open('fullschedule.xml', 'r').read()
    #doc = Schedule.fromXml(XML)
    #print 'Done!'
    
    #pprint.pprint( doc.toDict() )
    for day in doc.Days:
        print day.attr
        for time in day.times:
            print time.attr
            for show in time.Shows:
                #print show.name #, show.network, show.title, show.ep, #show.link
                pprint.pprint(show.toDict())
                #pprint.pprint(str(show.toDict()).encode('utf-8'))
    #    pprint.pprint(day.toDict())
    #    break

    #pprint.pprint( doc.toDict().encode('utf-8') )
    #url = 'http://services.tvrage.com/feeds/fullschedule.php?country=US'
    #doc = Schedule.loadFromUrl(url)
    
    #for days in doc.Days:
    #    pprint.pprint(days.toDict())
    #   break
    